﻿namespace BM.Tools.WebControls.MForm.Controls.ValueHandlers
{
    using System.ComponentModel;
    using System.Drawing.Design;
    using System.Runtime.Serialization;
    using System.Web.UI;
    using System.Web.UI.Design;

    using BM.Tools.WebControls.MForm.Controls.Items;

    /// <summary>
    /// The user control value handler binds the <see cref="LeafItem" /> control with a user control that is inside this value handler
    /// </summary>
    /// <typeparam name="T">
    /// the type of the user control 
    /// </typeparam>
    public abstract class UserControlValueHandler<T> : ControlValueHandler<T> where T : UserControl, new()
    {
        /// <summary>
        /// Gets or sets Src.
        /// </summary>
        /// <value>
        /// The source of the user control.
        /// </value>
        [Editor(typeof(UserControlFileEditor), typeof(UITypeEditor))]
        [UrlProperty("*.ascx")]
        public string Src
        {
            get;
            set;
        }

        /// <summary>
        /// Register control state requirement and loads the user control
        /// </summary>
        /// <param name="e">
        /// The event args.
        /// </param>
        protected override void OnInit(System.EventArgs e)
        {
            LoadControl();
            base.OnInit(e);
        }

        private void LoadControl()
        {
            Control c = Page.LoadControl(Src);
            T t = c as T;
            if (t == null)
            {
                throw new InvalidDataContractException(
                        "The Src property of the " + GetType().Name + " leads to a user control of type "
                        + c.GetType().Name);
            }

            Control = t;
        }
    }
}